package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Package: com.atguigu.tingshu.user.strategy.impl
 *
 * @author xiongkunYang
 * @description: 处理购买项目类型 ItemType 为声音的情况
 * @since 2025/6/26 10:11
 */
@Slf4j
@Component(SystemConstant.ORDER_ITEM_TYPE_TRACK)
public class TrackStrategyImpl implements ItemTypeStrategy {

    private final UserPaidTrackMapper userPaidTrackMapper;
    private final AlbumFeignClient albumFeignClient;

    public TrackStrategyImpl(UserPaidTrackMapper userPaidTrackMapper, AlbumFeignClient albumFeignClient) {
        this.userPaidTrackMapper = userPaidTrackMapper;
        this.albumFeignClient = albumFeignClient;
    }

    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        log.info("处理购买项目类型为：声音");
        String orderNo = userPaidRecordVo.getOrderNo();
        Long userId = userPaidRecordVo.getUserId();
        // 查询声音购买记录
        List<Long> trackIdList = userPaidRecordVo.getItemIdList();
        Long count = this.userPaidTrackMapper.selectCount(new LambdaQueryWrapper<UserPaidTrack>()
                .eq(UserPaidTrack::getUserId, userId)
                .in(UserPaidTrack::getTrackId, trackIdList));
        if (count > 0) {
            log.error("用户:{} 已购买过声音:{} ! ", userId, trackIdList.toString());
            return;
        }

        // 远程调用查询声音信息，获取声音所属专辑id
        Result<TrackInfo> trackInfoResult = albumFeignClient.getTrackInfoById(trackIdList.get(0));
        if (ResultCodeEnum.FAIL.getCode().equals(trackInfoResult.getCode())) {
            throw new GuiguException(ResultCodeEnum.REMOTE_ERROR);
        }
        Long albumId = trackInfoResult.getData().getAlbumId();
        // 遍历购买项目ID集合批量新增声音购买记录
        trackIdList.forEach(trackId -> {
            UserPaidTrack userPaidTrack = new UserPaidTrack();
            userPaidTrack.setOrderNo(orderNo);
            userPaidTrack.setUserId(userId);
            userPaidTrack.setAlbumId(albumId);
            userPaidTrack.setTrackId(trackId);
            userPaidTrackMapper.insert(userPaidTrack);
        });
    }
}